package cn.com.jcoo.security;

import cn.com.jcoo.StringUtils;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.ContextualSerializer;

import java.io.IOException;

public class SensitiveDataSerializer extends JsonSerializer<String>
		implements ContextualSerializer {

	private SensitiveData sensitiveData;

	public SensitiveDataSerializer(SensitiveData sensitiveData) {
		this.sensitiveData = sensitiveData;
	}

	public SensitiveDataSerializer() {

	}

	@Override
	public void serialize(String value, JsonGenerator gen, SerializerProvider serializers)
			throws IOException {
		if (StringUtils.isBlank(value)) {
			gen.writeString(value);
			return;
		}
		value = sensitiveData == null ? value
				: DesensitizeUtils.desensitize(value, sensitiveData.prefix(),
						sensitiveData.suffix());
		gen.writeString(value);

	}

	@Override
	public JsonSerializer<?> createContextual(SerializerProvider prov,
			BeanProperty property) {
		SensitiveData annotation = property.getAnnotation(SensitiveData.class);

		if (annotation != null) {
			return new SensitiveDataSerializer(annotation);
		}
		return this;
	}

	private String replaceByLength(String rawStr, int length, String replaceString,
			boolean fromLeft) {
		if (StringUtils.isBlank(rawStr)) {
			return rawStr;
		}
		if (rawStr.length() <= length) {
			return rawStr.replaceAll("[\\s\\S]", replaceString);
		}

		if (fromLeft) {
			return getSpecStringSequence(length, replaceString)
					+ rawStr.substring(length);
		}
		else {
			return rawStr.substring(0, length)
					+ getSpecStringSequence(length, replaceString);
		}
	}

	private String getSpecStringSequence(int length, String str) {
		return String.valueOf(str).repeat(Math.max(0, length));
	}
}
